<template>
  <div class="attendance_result_report">
    <div class="tool select">
<!--      <ToolBar :update-data="updateById"></ToolBar>-->
<!--      <el-row class="select" style="margin-left: 0.5rem;">-->
        <el-form :inline="true">
          <el-form-item label="部门:">
            <el-select v-model="form.depts" placeholder="请选择部门..." @change="deptChange" size="small" multiple
                       filterable clearable>
              <el-option :label="item.deptLevel2" :value="item.deptLevel2" v-for="item in deptList">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="组别:">
            <el-select v-model="form.groupNames" placeholder="请选择组别..."  @change="handleCurrentChange(1)" size="small" multiple
                       filterable clearable>
              <el-option :label="item.groupName" :value="item.groupName" v-for="item in groupList">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="姓名:">
            <el-select v-model="form.userIds" placeholder="请选择员工姓名..." size="small"  value-key="id" filterable clearable multiple :collapse-tags="true" style="width: 20vw;">
              <el-option :label="item.userName+'（'+item.jobNo+'）'" :value="item.userId" v-for="item in $store.state.userList">
                <span style="float: left">{{ item.userName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.jobNo }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出勤日期：">
            <el-date-picker  v-model="form.attendanceDate" size="small"
                            type="month"
                            align="left"
                             :clearable="false">
            </el-date-picker>
          </el-form-item>
          <el-form-item>


          <el-button type="primary" size="small" @click="handleCurrentChange(1)">筛选</el-button>
          <el-button type="primary" @click="reSet" size="small"
                     icon="el-icon-refresh">重置
          </el-button>
          <el-button type="primary" size="small" @click="goGetData">计算月数据
          </el-button>
          <el-button type="primary" size="small" @click="exportData(false)">导出本页</el-button>
          <el-button type="primary" size="small" @click="exportData(true)">导出全部</el-button>
          </el-form-item>
        </el-form>

<!--      </el-row>-->
    </div>
    <el-dialog title="打卡数据搜索" :visible.sync="dialogFormVisible" center>
      <el-row>
        <el-form :model="form">
          <el-col :span="12">
            <el-form-item label="入职时间" :label-width="formLabelWidth">
              <el-date-picker
                  class="w100"
                  v-model="form.hiredDate"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="档案时间" :label-width="formLabelWidth">
              <el-date-picker
                  class="w100"
                  v-model="form.archivesDate"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工姓名" :label-width="formLabelWidth">
              <el-select v-model="form.name" placeholder="请选择员工姓名..." value-key="id"
                         filterable clearable class="w100">
                <el-option :label="item.userName+'（'+item.jobNo+'）'" :value="item.name" v-for="item in dingUsersList" :key="item.id">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.jobNumber }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考勤结果" :label-width="formLabelWidth">
              <el-select v-model="form.timeResult" placeholder="请选择考勤结果..." value-key="id" filterable clearable
                         class="w100">
                <el-option :label="item.label" :value="item.value" v-for="item in timeResultList" :key="item.id">
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="getDataList">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="考勤时间计算" :visible.sync="getDataDialogFormVisible" center>
      <el-row>
        <el-form :model="form" label-width="8rem">
          <el-row>
            <el-col :span="12">
              <el-form-item label="员工姓名：">
                <el-select v-model="form.userIds" size="small" class="w100" value-key="userId" multiple
                           filterable clearable>
                  <el-option :label="item.userName+'（'+item.jobNo+'）'" :value="item.userId" v-for="item in $store.state.userList">
                    <span style="float: left">{{ item.userName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.jobNo }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门：">
                <el-select v-model="form.depts" size="small" class="w100" multiple :collapse-tags="true" style="width: 20vw;"
                           filterable clearable>
                  <el-option :label="item.deptLevel2" :value="item.deptLevel2" v-for="item in deptList">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="24">
            <el-form-item label="考勤年月：">
            <el-date-picker size="small" class="w100"
                v-model="form.start"
                type="month"
                placeholder="选择月"
                            :clearable="false">
            </el-date-picker>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="getDataDialogFormVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="getDataFromDingDing">确 定</el-button>
      </div>
    </el-dialog>

    <el-table
        id="table-detail"
        :data="tableData"
         border
        highlight-current-row
        :row-class-name="tableRowClassName"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}">
      <!--      <el-table-column prop="userid"></el-table-column>-->
      <el-table-column label="员工姓名" prop="fullname"  width="100">
      </el-table-column>
      <el-table-column label="工号" prop="jobno">
      </el-table-column>
      <el-table-column label="职位" prop="position" min-width="120">
      </el-table-column>
      <el-table-column label="薪资属性" prop="salarycategory" min-width="120">
      </el-table-column>
      <el-table-column label="招聘渠道" prop="offerchannel" min-width="120">
      </el-table-column>
      <el-table-column label="所在部门" prop="dept" :show-overflow-tooltip="true" min-width="100">
      </el-table-column>
      <el-table-column label="所在组别" prop="groupname" :show-overflow-tooltip="true" min-width="100">
      </el-table-column>
      <el-table-column label="月份" prop="attendancedate" min-width="100">
        <template slot-scope="scope" v-if="scope.row.attendancedate">
          {{ scope.row.attendancedate|formatDateMonth }}
        </template>
      </el-table-column>
      <el-table-column label="计算时间" prop="attendancedate" min-width="150" :show-overflow-tooltip="true">
        <template slot-scope="scope" v-if="scope.row.createtime">
          {{ scope.row.createtime|formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="出勤(天)">
        <el-table-column label="应出勤" prop="shouldarrive" width="100">
        </el-table-column>
        <el-table-column label="出勤合计" prop="totalattendance" width="100">

        </el-table-column>
        <el-table-column label="平时出勤" prop="dailyattendance" width="100">

        </el-table-column>
        <el-table-column label="周末出勤" prop="weekendattendance" width="100">
        </el-table-column>
        <el-table-column label="夜班天数" prop="nightshift" width="100">
        </el-table-column>

        <el-table-column label="总工时(小时)" prop="totalhours"  width="120">
        </el-table-column>
      </el-table-column>
      <el-table-column label="加班(小时)">
        <el-table-column label="基本加班" prop="dailyovertime" width="100">
        </el-table-column>
        <el-table-column label="连班加班" prop="continuousshift" width="100">
        </el-table-column>
        <el-table-column label="周末加班" prop="overtimeweekends" width="100">
        </el-table-column>
      </el-table-column>
      <el-table-column label="请假/出差(小时)">
        <el-table-column label="事假" prop="compassionateleave" width="80">
        </el-table-column>
        <el-table-column label="病假" prop="sickleave" width="80">
        </el-table-column>
        <el-table-column label="出差" prop="businesstravel" width="80">
        </el-table-column>
      </el-table-column>
      <el-table-column label="迟早旷（次）">
        <el-table-column label="迟到" prop="late" width="80">
        </el-table-column>
        <el-table-column label="早退" prop="leaveearly" width="80">
        </el-table-column>
        <el-table-column label="旷工" prop="absenteeism" width="80">
        </el-table-column>
      </el-table-column>
      <template v-for="item in monthData">
        <el-table-column :label="item.date+'（'+item.day+'）'+'小时'">
          <el-table-column label="基本出勤" :show-overflow-tooltip="true" :prop="'basicattendance'+item.dayIndex" min-width="100">
            <template slot-scope="scope">
              <span @click="getDingAttendanceDetail(scope.row,scope.row['basicattendance'+item.dayIndex],item.year+'-'+item.date)">{{scope.row['basicattendance'+item.dayIndex]}}</span>
            </template>
          </el-table-column>
          <el-table-column label="基本加班" :prop="'basicovertime'+item.dayIndex"  width="100">
          </el-table-column>
          <el-table-column label="超时加班" :prop="'overtime'+item.dayIndex"  width="100">
          </el-table-column>
          <el-table-column label="总时长" :prop="'totalduration'+item.dayIndex"  width="100">
          </el-table-column>
          <el-table-column show-overflow-tooltip label="备注" :prop="'summary'+item.dayIndex"  width="100">
          </el-table-column>
        </el-table-column>
      </template>

<!--      <el-table-column label="计算时间" prop="createtime" width="100" :show-overflow-tooltip="true">-->
<!--        <template slot-scope="scope">-->
<!--          {{ scope.row.createtime|formatDate }}-->
<!--        </template>-->
<!--        &lt;!&ndash;        <template slot-scope="scope">&ndash;&gt;-->
<!--        &lt;!&ndash;          <span @click="getDingAttendanceDetail(scope.row)"> {{ scope.row.summary }}</span>&ndash;&gt;-->
<!--        &lt;!&ndash;        </template>&ndash;&gt;-->
<!--      </el-table-column>-->
    </el-table>
    <div class="block">
      <el-pagination
          hide-on-single-page
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[size, size*2, size*3, size*4,this.total]"
          :page-size=size
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
    <el-drawer
        title="打卡数据"
        :visible.sync="drawer"
        :direction="direction"
        :before-close="handleClose">
      <div slot="title">
        <h2>{{ row.fullname }}打卡数据({{ selectedDataAttendanceDate|formatDateBirth }})</h2>
      </div>
      <div style="margin-left: 2rem">
        <el-descriptions :title="'打卡类型:'+item.checkType" v-for="item in attendanceResultList" column=1  :key="item.id">
          <el-descriptions-item label="标准打卡时间">{{ item.baseCheckTime|formatDate }}</el-descriptions-item>
          <el-descriptions-item label="实际打卡时间">{{ item.userCheckTime|formatDate }}</el-descriptions-item>
          <el-descriptions-item label="数据来源">{{ item.sourceType }}</el-descriptions-item>
          <el-descriptions-item label="打卡结果">{{ item.timeResult }}</el-descriptions-item>
        </el-descriptions>
        备注：
        <el-tag type="danger" v-text="row.summary"></el-tag>
      </div>

    </el-drawer>

  </div>
</template>

<script>
import ToolBar from "@/components/common/ToolBar";
import moment from "moment";

export default {
  name: "attendanceResultReportList",
  components: {ToolBar},
  data() {
    return {
      currentPage: 1,
      total: 0,
      size: 10,
      tableData: [],
      dingUsersListName: null,
      dingUsersList: [],
      userList: [],
      attendanceDate: null,
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          },
          {
            text: '一个月前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', date);
            }
          }]
      },
      dialogFormVisible: false,
      getDataDialogFormVisible: false,
      form: {
        start: null,
        end: null,
        userId: null,
        name: null,
        workDate: null,
        timeResult: null,
        checkType: null,
        archivesDate: new Date(),
        hiredDate: null,
        attendanceDate: moment().add("months",-1).format("YYYY-MM-01")
      },
      formLabelWidth: '120px',
      timeResultList: [
        {
          label: "正常",
          value: "Normal",
        },
        {
          label: "早退",
          value: "Early",
        }, {
          label: "迟到",
          value: "Late",
        }, {
          label: "严重迟到",
          value: "SeriousLate",
        }, {
          label: "旷工迟到",
          value: "Absenteeism",
        }, {
          label: "未打卡",
          value: "NotSigned",
        },
      ],
      drawer: false,
      direction: 'rtl',
      attendanceResultList: [],
      popoverShow: false,
      row: {},
      monthData: [],
      selectedDataAttendanceDate:null,
      deptList:[],
      groupList:[]
    }
  },
  created() {
    this.getDataList()


  },
  mounted() {
    // this.$tools.getMonthData(this.form.start)
    this.getDeptList()
  },
  methods: {
    getDeptList(){
      axios.get("/fin_user_roster/deptList").then(res=>{
        if(res.data.success){
          this.deptList=res.data.data
        }else{
          this.deptList=[]
        }
      })
    },
    deptChange(){
      if(this.form.dept!==null){
        this.getGroupList()

      }
    },
    getGroupList(){
      let data={
        depts:this.form.depts
      }
      axios.post("/fin_user_roster/groupList",data).then(res=>{
        if(res.data.success){
          this.groupList=res.data.data
        }else{
          this.groupList=[]
        }
      })
    },
    getObjectProperty(scope,dayIndex) {
      return eval("scope.row.basicattendance" +dayIndex);
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
    },
    tableRowClassName({row, rowIndex}) {
      if ((row.basicattendance < 8 || row.basicattendance === null) && row.week !== '七') {
        return 'error-row';
      }
      return '';
    },
    goGetData() {
      this.getDataDialogFormVisible = true
      this.form.start=this.form.attendanceDate
    },
    handleEdit(index, row) {
      console.log(index, row);
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    getDataList() {
      this.dialogFormVisible = false
      // this.form.start=this.attendanceDate[0]
      // this.form.end=this.attendanceDate[1]
      console.log("查询数据：", this.form)
      axios.post("/attendance_result_month_report/list/" + this.currentPage + "/" + this.size, this.form).then(res => {
        console.log("打卡信息：", res)
        if (res.data.success) {
          this.tableData = res.data.data.records

          Object.freeze(this.tableData)
          this.total = res.data.data.total
          this.pages = res.data.data.pages
          if (this.tableData.length > 0) {
            this.attendanceDate = this.tableData[0].attendancedate
            console.log("ThisAttendanceDate:", this.attendanceDate)
            this.monthData = this.$tools.getMonthData(this.attendanceDate)
          }
        } else {
          this.tableData = []
          this.total = 0
          this.pages = 1
        }

      })

    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getDataList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getDataList()
    },
    goSearch() {
      this.dialogFormVisible = true

    },
    reSet() {
      this.form = {
        start: null,
        end: null,
        userId: null,
        name: null,
        workDate: null,
        timeResult: null,
        checkType: null,
        attendanceDate: new Date().getTime() - 3600 * 1000 * 24
      }
      this.getDataList()
    },
    handleChange() {
      this.getDataList()
    },
    getDataFromDingDing() {
      // this.form.start = this.attendanceDate[0]
      // this.form.end = this.attendanceDate[1];
      console.log("查询数据：", this.form)
      axios.post("/attendance_result_month_report/get", this.form).then(res => {
        if (res.data.success) {
          this.getDataList()
          this.getDataDialogFormVisible = false;
          this.$tools.showNotification(res.data.message,"计算结果","success")

        }else{
          this.$tools.showNotification(res.data.message,"计算结果","error")

        }

      })
    },
    getDingAttendanceDetail(row,summary,workDate) {
      this.selectedDataAttendanceDate=workDate
      console.log("row:",row)
      this.row=row
      this.row.workDate=workDate
      this.row.summary=summary
      console.log("row:",row)

      const data = {
        workDate: workDate,
        userId: row.userid,
      }

      console.log("Data:", data)
      axios.post("/ding_attendance_result/getDetail", data).then(res => {
        console.log("Res:", res)
        if (res.data.success) {
          this.attendanceResultList = res.data.data
        } else {
          this.attendanceResultList = []
        }
      })
      this.drawer = true
    },
    exportData(all) {
      let filename = '四川瀚海' + moment(this.form.attendanceDate).format('YYYY年MM月') +(!this.form.dept?'':this.form.dept)+(!this.form.groupName?'':this.form.groupName)+ '月考勤信息.xlsx';
      if(!all){
        // 导出当前页
        this.form.page = this.currentPage;
        this.form.limit = this.size;
      }else {
        this.form.page = null;
        this.form.limit = null;
      }
      axios({
        method: 'post',
        url: '/excel/attendanceMonthResultReport', // 后端接口地址
        responseType: 'blob', // 表明返回数据是二进制文件
        data: this.form
      }).then(response => {
        fdCommon.down(filename,response.data)
      }).catch(error => {
        console.error('导出 Excel 失败:', error);
      });
    }

  },



}
</script>

<style scoped lang="less">
.el-input--suffix .el-input__inner {
  padding-right: 0!important;
}
.attendance_result_report {
  .select {
    //margin-bottom: 0.5rem;
    display: inline-flex !important;
    .el-input--suffix .el-input__inner{
      padding-right: 0 !important;
    }
  }
  .el-input--suffix .el-input__inner {
    padding-right: 0!important;
  }
}

</style>
